package com.wsj.aop;

import com.wsj.services.ProxyTest;
import com.wsj.services.impl.ProxyTestImpl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * description:JDK Proxy：通过它的newProxyInstance函数来获得代理对象，学习JdkDynamicAopProxy
 *
 * 1、构造函数，将代理的对象传入 2、invoke方法，此方法中实现了AOP增强的所有逻辑 3、getProxy方法，必不可少
 *
 * @author yang
 * @date 2019/2/19 15:01
 */
public class JdkInvocationHandler implements InvocationHandler {

  //目标对象
  private Object target;

  private JdkInvocationHandler(Object target) {
    this.target = target;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("Before invocation");
    //执行目标对象的方法
    Object retVal = method.invoke(target, args);
    System.out.println("After invocation");
    return retVal;
  }

  public static void main(String[] args) {
    ProxyTestImpl proxyObj = new ProxyTestImpl();
    JdkInvocationHandler jdkInvocationHandler = new JdkInvocationHandler(proxyObj);
    //getProxy：通过Proxy.newProxyInstance生成代理对象
    ProxyTest proxy = (ProxyTest) Proxy.newProxyInstance(
        ProxyTest.class.getClassLoader(),
        ProxyTestImpl.class.getInterfaces(), jdkInvocationHandler);
    proxy.print();
  }
}



